package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.equipment.entity.*;
import com.mxpio.erp.common.equipment.service.*;
import com.mxpio.erp.common.equipment.vo.VEquipmentStockCkPosting;
import com.mxpio.erp.common.equipment.vo.VEquipmentStockInventory;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description: tpm_stock_ck_apply
 * @Author: jeecg-boot
 * @Date:   2021-10-14
 * @Version: V1.0
 */
@Service
public class EquipmentStockCkApplyServiceImpl extends BaseServiceImpl<EquipmentStockCkApply> implements EquipmentStockCkApplyService {

	@Resource
	private EquipmentStockCkApplyItemService tpmStockCkApplyItemService;
	@Resource
	private EquipmentStockCkHistoryService ckHistoryService;
	@Resource
	private EquipmentStockRejectHistoryService rejectHistoryService;
	@Resource
	private EquipmentStockItemInventoryService inventoryService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
        JpaUtil.lind(EquipmentStockCkApplyItem.class).equal("ckApplyId", id).delete();
        delete(EquipmentStockCkApply.class,id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
            JpaUtil.lind(EquipmentStockCkApplyItem.class).equal("ckApplyId", id).delete();
            delete(EquipmentStockCkApply.class,id);
		}
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public String submit(EquipmentStockCkApply tpmStockCkApply,List<EquipmentStockCkApplyItem> itemList) {
		if (tpmStockCkApply.getStatus() == 0){
			tpmStockCkApply.setStatus(1);
		}else {
			return "只有待提交数据才可以进行提交!";
		}
		tpmStockCkApply.setVersion(tpmStockCkApply.getVersion()+1);
        this.update(tpmStockCkApply);
		itemList.forEach(item->{
			item.setStatus(1);
			item.setVersion(item.getVersion()+1);
		});
        tpmStockCkApplyItemService.update(itemList);
		return "提交成功!";
    }

	@Override
	public String changeStatus(EquipmentStockCkApply tpmStockCkApply, int status) {
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public synchronized void ckPosting(VEquipmentStockCkPosting tpmStockCkPostingVo) {
		List<VEquipmentStockInventory> inventoryVoList = tpmStockCkPostingVo.getInventoryVoList();
		if (inventoryVoList.size() < 1){
			return;
		}
		EquipmentStockCkApplyItem ckApplyItem = tpmStockCkPostingVo.getCkApplyItem();
		int type = tpmStockCkPostingVo.getType();
		AtomicBoolean isAllUpdate = new AtomicBoolean(true);
		//更新的list
		List<EquipmentStockCkApplyItem> ckApplyItemList = new ArrayList<>();
		List<EquipmentStockCkHistory> ckHistoryList = new ArrayList<>();
		inventoryVoList.forEach(inventoryVo ->{
			//判断状态是否需要更新
			int remainder = ckApplyItem.getApplyNumber() - ckApplyItem.getAlreadyOutNumber();
			if (inventoryVo.getOutNumber().equals(remainder)){
				//出库完成，变更详情状态
				ckApplyItem.setStatus(2);
				ckApplyItem.setVersion(ckApplyItem.getVersion()+1);
				ckApplyItemList.add(ckApplyItem);
			}else if (inventoryVo.getOutNumber() > remainder){
				inventoryVo.setOutNumber(remainder);
			}else {
				isAllUpdate.set(false);
			}
			//操作库存出库
			EquipmentStockItemInventory inventory = inventoryService.getById(EquipmentStockItemInventory.class,inventoryVo.getId());
			inventory.setCurrentOnhandQty(inventory.getCurrentOnhandQty().subtract(BigDecimal.valueOf(inventoryVo.getOutNumber())));
			inventoryService.update(inventory);
			//记录history
			EquipmentStockCkHistory tpmStockCkHistory = new EquipmentStockCkHistory(ckApplyItem,inventoryVo,type);
			ckHistoryList.add(tpmStockCkHistory);
		});
		tpmStockCkApplyItemService.update(ckApplyItemList);
		ckHistoryService.save(ckHistoryList);
		//判断所有主数据是否完成
		if (isAllUpdate.get()){
			List<EquipmentStockCkApplyItem> itemList = tpmStockCkApplyItemService.selectByMainId(ckApplyItem.getCkApplyId());
			AtomicBoolean doneStatus = new AtomicBoolean(true);
			itemList.forEach(item->{
				if (item.getStatus() != 2){
					doneStatus.set(false);
				}
			});
			if (doneStatus.get()){
                String sql ="update MB_ERP_EQUIPMENT_STOCK_CK_APPLY\n" +
                        "\t\tset status = 2\n" +
                        "\t\twhere id = "+ckApplyItem.getCkApplyId();
                JpaUtil.nativeQuery(sql);
//				tpmStockCkApplyMapper.updateStatusById(2,ckApplyItem.getCkApplyId());
			}
		}
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public synchronized void ckReject(VEquipmentStockCkPosting tpmStockCkPostingVo){
		List<EquipmentStockCkApplyItem> ckApplyItemList = tpmStockCkPostingVo.getCkPostingItemList();
		if (ckApplyItemList.size() < 1){
			return;
		}
		int type = tpmStockCkPostingVo.getType();
		String rejectReason = tpmStockCkPostingVo.getRejectReason();
		//更新的list
		List<EquipmentStockCkHistory> ckHistoryList = new ArrayList<>();
		List<EquipmentStockRejectHistory> rejectHistoryList = new ArrayList<>();
		ckApplyItemList.forEach(ckApplyItem ->{
			//拒绝出库，直接变更状态
			ckApplyItem.setStatus(2);
			ckApplyItem.setVersion(ckApplyItem.getVersion() + 1);
			//拒绝，保存拒绝记录
			EquipmentStockRejectHistory rejectHistory = new EquipmentStockRejectHistory(ckApplyItem.getCkApplyId(),1,rejectReason);
			rejectHistoryList.add(rejectHistory);
			//记录history
			EquipmentStockCkHistory tpmStockCkHistory = new EquipmentStockCkHistory(ckApplyItem, type);
			ckHistoryList.add(tpmStockCkHistory);
		});
		tpmStockCkApplyItemService.update(ckApplyItemList);
		ckHistoryService.save(ckHistoryList);
		rejectHistoryService.save(rejectHistoryList);
		//判断所有主数据是否完成
		List<EquipmentStockCkApplyItem> itemList = tpmStockCkApplyItemService.selectByMainId(ckApplyItemList.get(0).getCkApplyId());
		AtomicBoolean doneStatus = new AtomicBoolean(true);
		itemList.forEach(item->{
			if (item.getStatus() != 2){
				doneStatus.set(false);
			}
		});
		if (doneStatus.get()){
		    String sql ="update MB_ERP_EQUIPMENT_STOCK_CK_APPLY\n" +
                    "\t\tset status = 2\n" +
                    "\t\twhere id = "+ckApplyItemList.get(0).getCkApplyId();
            JpaUtil.nativeQuery(sql);
//			tpmStockCkApplyMapper.updateStatusById(2,ckApplyItemList.get(0).getCkApplyId());
		}
	}

}
